package com.group.yztcedu.playlive.main.home;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.group.yztcedu.playlive.R;
import com.group.yztcedu.playlive.base.BaseFragment;
import com.group.yztcedu.playlive.bean.HomeChannelsBean;
import com.group.yztcedu.playlive.bean.HomeDataBean;
import com.group.yztcedu.playlive.bean.HomeHotUsersBean;
import com.group.yztcedu.playlive.bean.HomeRecommendTagsBean;
import com.group.yztcedu.playlive.config.UrlConfig;
import com.group.yztcedu.playlive.main.home.adapter.HotUserAdapter;
import com.group.yztcedu.playlive.main.home.adapter.ImagePagerAdapter;
import com.group.yztcedu.playlive.main.home.adapter.ListViewAdapter;
import com.group.yztcedu.playlive.widget.MyGridView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class HomeFragment extends BaseFragment implements HomeContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_points)
    LinearLayout llPoints;
    @BindView(R.id.home_gridView_zb)
    MyGridView homeGridViewZb;
    @BindView(R.id.home_listView)
    ListView homeListView;
    @BindView(R.id.image_vp)
    ViewPager imageVp;
    @BindView(R.id.home_swipeRefreshLayout)
    SwipeRefreshLayout homeSwipeRefreshLayout;
    private HomeContract.Model model;
    private HomeContract.Presenter presenter;
    private Handler handler = new Handler();
    private HomeDataBean mHomeDataBean;
    private List<HomeChannelsBean> mHomeChannelsBeanList;
    private List<HomeHotUsersBean> mHomeHotUsersBeanList;
    private List<HomeRecommendTagsBean> mHomeRecommendTagsList;
    private ImagePagerAdapter imagePagerAdapter;
    private int page = 1;
    private AutoRunTask autoRunTask = new AutoRunTask();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            super.handleMessage(msg);
            if (msg.what == 1) {
                int index = msg.arg1;
                imageVp.setCurrentItem(index);
            }
        }
    };
    private HotUserAdapter hotAdapter;
    private ListViewAdapter listViewAdapter;
    private View points;

    public HomeFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        model = new HomeModel();
        presenter = new HomePresenter(this, model);
        presenter.initData(initParams(page));
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //设置下拉出现小圆圈是否是缩放出现，出现的位置，最大的下拉位置
        homeSwipeRefreshLayout.setProgressViewOffset(true, 50, 200);
//设置下拉圆圈的大小，两个值 LARGE， DEFAULT
        homeSwipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
// 设置下拉圆圈上的颜色，蓝色、绿色、橙色、红色
        homeSwipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

// 通过 setEnabled(false) 禁用下拉刷新
        homeSwipeRefreshLayout.setEnabled(true);

// 设定下拉圆圈的背景
// .setProgressBackgroundColor(R.color.red);
/*
 * 设置手势下拉刷新的监听
 */
        homeSwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        // 刷新动画开始后回调到此方法
                        presenter.initData(initParams(++page));
                    }
                }
        );

    }

    private void initView() {
        mHomeRecommendTagsList = new ArrayList<>();
        listViewAdapter = new ListViewAdapter(mHomeRecommendTagsList);
        homeListView.setAdapter(listViewAdapter);
        mHomeDataBean = new HomeDataBean();
        //轮播图
        mHomeChannelsBeanList = new ArrayList<>();
        //推荐主播
        mHomeHotUsersBeanList = new ArrayList<>();
        hotAdapter = new HotUserAdapter(mHomeHotUsersBeanList);
        homeGridViewZb.setAdapter(hotAdapter);
//        homeGridViewZb.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//
//            }
//        });
    }

    private void initAutoRun() {
        for (int i = 0; i < mHomeChannelsBeanList.size(); i++) {
            points = new View(getActivity());
            if(points !=null){
            points.setBackgroundResource(R.mipmap.dot_enable);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
            params.leftMargin = 2;
            points.setLayoutParams(params);
            llPoints.addView(points);
            }
        }
        //初始化标题
        tvTitle.setText(mHomeChannelsBeanList.get(0).getChannelName());
        //初始化小圆点
        llPoints.getChildAt(0).setBackgroundResource(R.mipmap.dot_normal);

        imageVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                tvTitle.setText(mHomeChannelsBeanList.get(position % mHomeChannelsBeanList.size()).getChannelName());
                //小圆点项目
                for (int i = 0; i < llPoints.getChildCount(); i++) {
                    llPoints.getChildAt(i).setBackgroundResource(R.mipmap.dot_enable);
                }
                llPoints.getChildAt(position % mHomeChannelsBeanList.size()).setBackgroundResource(R.mipmap.dot_normal);
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        autoRunTask.startRun();
        imageVp.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        autoRunTask.stopRun();
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        autoRunTask.startRun();
                        break;
                }
                return false;
            }
        });
    }


    private HashMap<String, String> initParams(int page) {
        HashMap<String, String> params = new HashMap<>();
        params.put(UrlConfig.Key.PAGE, "" + page);
        params.put(UrlConfig.Key.VERSION_CODE, "20025");
        return params;
    }

    @Override
    public void onSuccessGetHomeData(final HomeDataBean homeDataBeen) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                mHomeDataBean = homeDataBeen;
                //轮播
                mHomeChannelsBeanList.clear();
                mHomeChannelsBeanList.addAll(mHomeDataBean.getChannels());
                imageVp.setCurrentItem(1000 * mHomeChannelsBeanList.size());
                if (mHomeChannelsBeanList.size() !=0) {
                    llPoints.removeAllViews();
                    initAutoRun();
                }
                imagePagerAdapter = new ImagePagerAdapter(mHomeChannelsBeanList);
                imageVp.setAdapter(imagePagerAdapter);
                imagePagerAdapter.notifyDataSetChanged();
                //推荐直播
                mHomeHotUsersBeanList.clear();
                mHomeHotUsersBeanList.addAll(mHomeDataBean.getHotUsers());
                hotAdapter.notifyDataSetChanged();
                //变化条目集合
                mHomeRecommendTagsList.clear();
                mHomeRecommendTagsList.addAll(homeDataBeen.getRecommendTags());
                listViewAdapter.notifyDataSetChanged();
                homeSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void onFailGetHomeData(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();

    }

    class AutoRunTask implements Runnable {
        private int delayTime = 3000;
        private boolean isStart = false;

        //开始线程任务
        public void startRun() {
            if (!isStart) {
                //关闭之前所有正在执行的任务
                mHandler.removeCallbacks(this);
                isStart = true;
                //要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作
                mHandler.postDelayed(this, delayTime);
            }
        }

        //停止线程
        public void stopRun() {
            if (isStart) {
                isStart = false;
                mHandler.removeCallbacks(this);
            }
        }

        @Override
        public void run() {
            int currentItem = imageVp.getCurrentItem();
            //发送消息
            Message msg = Message.obtain();
            msg.what = 1;
            msg.arg1 = ++currentItem;
            mHandler.sendMessage(msg);
            mHandler.postDelayed(this, delayTime);
        }
    }
}
